<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script>
    // 最大子数组的和
    function maxSunArray(nuns) {
      if (nuns.length < 1) return 0;
      let currentMax = nuns[0];
      let globalMax = nuns[0];

      for (let i = 1; i < nuns.length; i++) {
        // 选择延续当前子数组 或 以当前元素开始新子数组
        currentMax = Math.max(nuns[i], currentMax + nuns[i]);
        globalMax = Math.max(globalMax, currentMax);
      }

      console.log('globalMax: ', globalMax);
      return globalMax;
    }

    console.log(maxSunArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]));

    function maxSubArrayWithIndices(nums) {
      if (nums.length < 1) {
        return {
          sums: 0,
          start: -1,
          end: -1,
        };
      }

      let currentMax = nums[0];
      let globalMax = currentMax;
      let start = 0;
      let end = 0;
      let temp = 0;

      for (let i = 1; i < nums.length; i++) {
        if (nums[i] > currentMax + nums[i]) {
          currentMax = nums[i];
          temp = i;
        } else {
          currentMax += nums[i];
        }

        if (currentMax > globalMax) {
          globalMax = currentMax;
          start = temp;
          end = i;
        }
      }

      return {
        sum: globalMax,
        start,
        end,
      };
    }

    console.log(maxSubArrayWithIndices([-2, 1, -3, 4, -1, 2, 1, -5, 4]));
  </script>
  <body></body>
</html>
